/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.iwgang.example.slice;

import cn.iwgang.countdownview.CountdownView;


import cn.iwgang.example.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.app.Context;

import java.util.ArrayList;
import java.util.List;

/**
 * 倒计时列表使用功能入口
 */
public class ListContainerAbilitySlice extends AbilitySlice {
    private ArrayList<ItemInfo> mDataList;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_list_container);
        ListContainer list1 = (ListContainer) findComponentById(ResourceTable.Id_list);
        initData();
        MyListProvider myListProvider = new MyListProvider(this, mDataList);
        list1.setItemProvider(myListProvider);
    }

    private void initData() {
        mDataList = new ArrayList<>();

        for (int i = 1; i < 20; i++) {
            mDataList.add(new ItemInfo(1000 + i, "ListView_测试标题_" + i, i * 20 * 1000));
        }

        // 校对倒计时
        long curTime = System.currentTimeMillis();
        for (ItemInfo itemInfo : mDataList) {
            itemInfo.setEndTime(curTime + itemInfo.getCountdown());
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private void dealWithLifeCycle1(CountdownView countdownView, final int position) {
        countdownView.setBindStateChangedListener(new Component.BindStateChangedListener() {
            @Override
            public void onComponentBoundToWindow(Component component) {
                int pos = position;
                ItemInfo itemInfo = mDataList.get(pos);
                if (itemInfo.getEndTime() - System.currentTimeMillis() > 0) {
                    countdownView.start(itemInfo.getEndTime() - System.currentTimeMillis());
                } else {
                    countdownView.stop();
                    countdownView.allShowZero();
                }
                refreshTime(itemInfo.getEndTime() - System.currentTimeMillis());
            }

            private void refreshTime(long leftTime) {
                if (leftTime > 0) {
                    countdownView.start(leftTime);
                } else {
                    countdownView.stop();
                    countdownView.allShowZero();
                }
            }

            @Override
            public void onComponentUnboundFromWindow(Component component) {
                countdownView.stop();
            }
        });


    }

    static class ItemInfo {
        private int id;
        private String title;
        private long countdown;
        /**
         * 根据服务器返回的countdown换算成手机对应的开奖时间 (毫秒)
         * [正常情况最好由服务器返回countdown字段，然后客户端再校对成该手机对应的时间，不然误差很大]
         */
        private long endTime;

        public ItemInfo(int id, String title, int countdown) {
            this.id = id;
            this.title = title;
            this.countdown = countdown;
        }

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public long getCountdown() {
            return countdown;
        }

        public void setCountdown(long countdown) {
            this.countdown = countdown;
        }

        public long getEndTime() {
            return endTime;
        }

        public void setEndTime(long endTime) {
            this.endTime = endTime;
        }
    }

    static class MyListProvider extends RecycleItemProvider {
        private Context mContext;
        private List<ItemInfo> mDatas;


        public MyListProvider(Context context, List<ItemInfo> datas) {
            this.mContext = context;
            this.mDatas = datas;
        }

        @Override
        public int getCount() {
            return mDatas.size();
        }

        @Override
        public Object getItem(int i1) {
            return mDatas.get(i1);
        }

        @Override
        public long getItemId(int i1) {
            return i1;
        }

        @Override
        public Component getComponent(int i1, Component component, ComponentContainer componentContainer) {
            DependentLayout dependentLayout = (DependentLayout) LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_list_item, null, false);
            Text mTvTitle = (Text) dependentLayout.findComponentById(ResourceTable.Id_tv_title);
            CountdownView cvCountdownView = (CountdownView) dependentLayout.findComponentById(ResourceTable.Id_cv_countdownView);
            ItemInfo curItemInfo = mDatas.get(i1);
            mTvTitle.setText(curItemInfo.getTitle());
            dealWithLifeCycle(cvCountdownView, i1);
            return dependentLayout;
        }

        /**
         * 以下两个接口代替 activity.onStart() 和 activity.onStop(), 控制 timer 的开关
         *
         * @param countdownView 倒计时控件
         * @param position 列表条目
         */
        private void dealWithLifeCycle(CountdownView countdownView, final int position) {
            countdownView.setBindStateChangedListener(new Component.BindStateChangedListener() {
                @Override
                public void onComponentBoundToWindow(Component component) {
                    int pos = position;
                    ItemInfo itemInfo = mDatas.get(pos);
                    if (itemInfo.getEndTime() - System.currentTimeMillis() > 0) {
                        countdownView.start(itemInfo.getEndTime() - System.currentTimeMillis());
                    } else {
                        countdownView.stop();
                        countdownView.allShowZero();
                    }
                    refreshTime(itemInfo.getEndTime() - System.currentTimeMillis());
                }

                private void refreshTime(long leftTime) {
                    if (leftTime > 0) {
                        countdownView.start(leftTime);
                    } else {
                        countdownView.stop();
                        countdownView.allShowZero();
                    }
                }

                @Override
                public void onComponentUnboundFromWindow(Component component) {
                    countdownView.stop();
                }
            });


        }


        static class MyViewHolder {
            private Text mTvTitle;
            private CountdownView mCvCountdownView;
            private ItemInfo mItemInfo;

            /**
             * 初始化
             *
             * @param convertView 传入的控件
             */
            public void initView(Component convertView) {
                mTvTitle = (Text) convertView.findComponentById(ResourceTable.Id_tv_title);
                mCvCountdownView = (CountdownView) convertView.findComponentById(ResourceTable.Id_cv_countdownView);
            }

            /**
             * 绑定单个条目信息
             *
             * @param itemInfo 条目信息
             */
            public void bindData(ItemInfo itemInfo) {
                mItemInfo = itemInfo;
                mTvTitle.setText(itemInfo.getTitle());
                refreshTime(mItemInfo.getEndTime() - System.currentTimeMillis());
            }

            /**
             * 刷新时间显示
             *
             * @param leftTime 剩余时间
             */
            public void refreshTime(long leftTime) {
                if (leftTime > 0) {
                    mCvCountdownView.start(leftTime);
                } else {
                    mCvCountdownView.stop();
                    mCvCountdownView.allShowZero();
                }
            }

            /**
             * 获取单个条目信息
             *
             * @return 获得单个条目信息
             */
            public ItemInfo getBean() {
                return mItemInfo;
            }

            /**
             * 获取倒计时控件
             *
             * @return 获得倒计时控件
             */
            public CountdownView getCvCountdownView() {
                return mCvCountdownView;
            }
        }
    }
}
